﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Web;
using up7.db.biz;
using up7.db.model;
using up7.db.utils;
using up7.filemgr.app;
using up7.db.database.up7.sql;
using Newtonsoft.Json.Linq;

namespace up7.api.filemgr
{
    public partial class fd_create : WebBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String pid = this.reqStr("pid");
            String id = this.reqStr("id");
            String pathLoc = this.reqStr("pathLoc");
            String sizeLoc = this.reqStr("sizeLoc");
            String lenLoc = this.reqStr("lenLoc");
            String uid = this.reqStr("uid");
            String fCount = this.reqStr("filesCount");
            String pathRel = this.Server.UrlDecode(this.reqStr("pathRel"));
            String callback = this.reqStr("callback");
            pathLoc = PathTool.url_decode(pathLoc);

            if (string.IsNullOrEmpty(id)
                || string.IsNullOrEmpty(uid)
                || string.IsNullOrEmpty(pathLoc)
                )
            {
                this.toContentJson(callback + "({\"value\":null})");
                return;
            }

            FileInf fileSvr = new FileInf();
            fileSvr.id = id;
            fileSvr.pid = pid;
            fileSvr.pidRoot = "";
            fileSvr.fdChild = false;
            fileSvr.fdTask = true;
            fileSvr.uid = uid;//将当前文件UID设置为当前用户UID
            fileSvr.nameLoc = Path.GetFileName(pathLoc);
            fileSvr.pathLoc = pathLoc;
            fileSvr.pathRel = PathTool.combin(pathRel, fileSvr.nameLoc);
            fileSvr.lenLoc = Convert.ToInt64(lenLoc);
            fileSvr.fileCount = int.Parse(fCount);
            fileSvr.sizeLoc = sizeLoc;
            fileSvr.deleted = false;
            fileSvr.nameSvr = fileSvr.nameLoc;

            //生成路径，格式：upload/年/月/日/guid/文件夹名称
            PathGuidBuilder pb = new PathGuidBuilder();
            fileSvr.pathSvr = pb.genFolder(fileSvr);
            fileSvr.pathSvr = fileSvr.pathSvr.Replace("\\", "/");
            if (!Directory.Exists(fileSvr.pathSvr)) Directory.CreateDirectory(fileSvr.pathSvr);

            //保存层级结构
            FolderSchema fs = new FolderSchema();
            fs.create(fileSvr);

            //添加成根目录
            if (pathRel == "/")
            {
                SqlFile.build().Add(fileSvr);
            }//添加成子目录
            else
            {
                SqlFolder.build().add(fileSvr);
            }

            //触发事件
            up7_biz_event.folder_create(fileSvr);

            string json = JsonConvert.SerializeObject(fileSvr);
            json = HttpUtility.UrlEncode(json);
            json = json.Replace("+", "%20");
            var jo = new JObject { { "value", json } };
            json = callback + string.Format("({0})", JsonConvert.SerializeObject(jo));
            this.toContent(json);
        }
    }
}